package event_manager

import (
	"reflect"
)

type EventManager struct {
	listeners []EventListener
}

type EventListener interface {
	SetEvents()
	GetListenerEvents() []interface{}
	Handler(event interface{})
}

func (m *EventManager) Register(listener EventListener) {
	m.listeners = append(m.listeners, listener)
}

func (m *EventManager) getAllListeners() []EventListener {
	return m.listeners
}

func (m *EventManager) Dispatch(event interface{}) {
	// 查询到全部的 listener
	listeners := m.getAllListeners()

	for _, listener := range listeners {
		listener.SetEvents()
		listnerEvents := listener.GetListenerEvents()
		for _, listnerEvent := range listnerEvents {
			if reflect.TypeOf(event).String() == reflect.TypeOf(listnerEvent).String() {
				listener.Handler(event)
			}
		}
	}
}

var EM *EventManager

func init() {
	EM = new(EventManager)
}
